package com.hmdp.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.BooleanUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.hmdp.dto.Result;
import com.hmdp.entity.Shop;
import com.hmdp.mapper.ShopMapper;
import com.hmdp.service.IShopService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hmdp.utils.CacheClient;
import com.hmdp.utils.RedisConstants;
import com.hmdp.utils.RedisData;
import com.hmdp.utils.SystemConstants;
import jodd.util.StringUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.geo.Distance;
import org.springframework.data.geo.GeoResult;
import org.springframework.data.geo.GeoResults;
import org.springframework.data.redis.connection.RedisGeoCommands;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.domain.geo.GeoReference;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author 虎哥
 * @since 2021-12-22
 */
@Service
public class ShopServiceImpl extends ServiceImpl<ShopMapper, Shop> implements IShopService {

    @Autowired
    private StringRedisTemplate redisTemplate;


    private CacheClient cacheClient = new CacheClient(redisTemplate);


    /**
     * 通过id查询商品，首先查询缓存
     *
     * @param id
     * @return
     */
    @Override
    public Result queryById(Long id) {
        String key = RedisConstants.CACHE_SHOP_KEY + id;

        String shopJSON = redisTemplate.opsForValue().get(key);

        //判断商品是否存在，不存在则查数据库并写入缓存
        //商品信息存在，反序列化为shop对象后返回

        if (StrUtil.isNotBlank(shopJSON)) {  //只有当字符串有内容时才为真
            Shop shop = JSONUtil.toBean(shopJSON, Shop.class);
            return Result.ok(shop);
        }
        //商品信息缓存中不存在，查询数据库并写回redis，返回
        //判断缓存命中的是否为空值
        if (shopJSON != null) {
            return Result.fail("商品不存在！");
        }
        //查询数据库
        Shop shop = getById(id);
        if (shop == null) {
            //将空值写入redis，设置有效期为短有效期
            redisTemplate.opsForValue().set(key, "", RedisConstants.CACHE_NULL_TTL, TimeUnit.MINUTES);
            return Result.fail("商品不存在！");
        }
        redisTemplate.opsForValue().set(key, JSONUtil.toJsonStr(shop), RedisConstants.CACHE_SHOP_TTL, TimeUnit.MINUTES); //将shop序列化为json存储
        //缓存穿透——空对象解决
       /* Shop shop = cacheClient
                .queryWithPassThrough(RedisConstants.CACHE_SHOP_KEY, id, Shop.class, id1 -> getById(id1), RedisConstants.CACHE_SHOP_TTL, TimeUnit.MINUTES);
*/
        /*//缓存击穿——互斥锁解决
        Shop shop = cacheClient
                .queryWithMutex(RedisConstants.CACHE_SHOP_KEY, id, Shop.class, id1-> getById(id1),
                        RedisConstants.CACHE_SHOP_TTL, TimeUnit.MINUTES);*/

        /*//缓存击穿——逻辑过期解决
        Shop shop = cacheClient.
                queryWithLogicalExpire(RedisConstants.CACHE_SHOP_KEY, id, Shop.class, id1-> getById(id1), RedisConstants.CACHE_SHOP_TTL, TimeUnit.MINUTES);*/

        return Result.ok(shop);
    }



    /**
     * 更新商户信息
     *
     * @param shop
     * @return
     */
    @Override
    @Transactional
    public Result updateShop(Shop shop) {
        //确保当前商户存在
        if (shop.getId() == null)
            return Result.fail("当前商户不存在！");

        //写入数据库
        updateById(shop);

        //删除缓存
        String key = RedisConstants.CACHE_SHOP_KEY + shop.getId();
        redisTemplate.delete(key);

        return Result.ok();
    }


    /**
     * 根据商铺类型分页查询商铺信息
     * @param typeId 商铺类型
     * @param current 页码
     * @param x  经度
     * @param y  纬度
     * @return 商铺列表
     */
    @Override
    public Result queryShopByType(Integer typeId, Integer current, Double x, Double y) {
        //1、判断是否要根据经纬度查询
        if (x == null || y == null){    //原始查询数据库即可
            Page<Shop> page = query()
                    .eq("type_id", typeId)
                    .page(new Page<>(current, SystemConstants.DEFAULT_PAGE_SIZE));
            return Result.ok(page.getRecords());
        }

        //2、计算分页参数（查询redis时需要）
        int from = (current - 1) * SystemConstants.DEFAULT_PAGE_SIZE;
        int end = current * SystemConstants.DEFAULT_PAGE_SIZE;

        //3、查询redis，按照距离排序&分页，结果：shopId，距离
        String key = RedisConstants.SHOP_GEO_KEY + typeId;
        GeoResults<RedisGeoCommands.GeoLocation<String>> shopLocations = redisTemplate.opsForGeo()
                .search(
                        key,    //查询的商户类型
                        GeoReference.fromCoordinate(x, y),  //基于哪个坐标进行范围排序查询
                        new Distance(5000),  //以当前坐标5km范围进行搜索
                        RedisGeoCommands.GeoRadiusCommandArgs.newGeoRadiusArgs().includeDistance()    //让当前查询结果附带上距离查询坐标的距离
                                .limit(end)     //查询从0~end的数据，不查询全部数据
                );

        //3.1手动截取从from——end的数据
        if (shopLocations == null)
            return Result.ok();
        //3.1.1获取刚刚查询的结果，即包含shopId以及距离的列表
        List<GeoResult<RedisGeoCommands.GeoLocation<String>>> content = shopLocations.getContent();     //这是真正包含我们所需查询结果的对象
        //若没有下一页则无需继续
        if (content.size() <= from)
            return Result.ok();
        //3.1.2截取from-end（直接跳过from即可），并且收集shopId以及distance
        Map<String, Distance> map = new HashMap<>();    //用于匹配shopId以及对应distance的表
        List<Long> ids = new ArrayList<>();     //用于存储当前截取内容中shopId的列表
        content.stream().skip(from)
                .forEach(
                        result -> {
                            //获取shopId
                            String shopId = result.getContent().getName();
                            //获取距离
                            Distance distance = result.getDistance();
                            //存储id，以及id与distance匹配的信息
                            ids.add(Long.valueOf(shopId));
                            map.put(shopId, distance);
                        }
                );

        //4、解析id，根据id查询店铺
        String idStr = StrUtil.join(",", ids);  //ids的字符串形式
        List<Shop> shops = query().in("id", ids).last("ORDER BY FIELD(id," + idStr + ")").list();

        //5、将店铺赋予对应的distance
        for (Shop shop : shops) {
            shop.setDistance(map.get(shop.getId().toString()).getValue());
        }

        return Result.ok(shops);
    }

    /*//缓存击穿逻辑过期解决方案
    //将商户信息封装为redisData写入redis
    public void putShopToRedis(Long id, Long expireTime){
        //查询店铺信息
        Shop shop = getById(id);

        //设置redis数据对象
        RedisData redisData = new RedisData();
        redisData.setData(shop);
        redisData.setExpireTime(LocalDateTime.now().plusMinutes(expireTime));

        //存入redis数据库
        String key = RedisConstants.CACHE_SHOP_KEY + id;
        redisTemplate.opsForValue().set(key, JSONUtil.toJsonStr(redisData));
    }*/
}
